package user

import (
	"encoding/json"
	"ginfwk/common/mock/admin"
	"ginfwk/common/mock/mhelper"
	"ginfwk/infrastructure/component/logger"
	"ginfwk/infrastructure/facede"
	"ginfwk/infrastructure/helper/ghttp"
	"github.com/gin-gonic/gin"
	"time"
)

type UserInfo struct {
}

func (u *UserInfo) GetAdminUserInfo(g *gin.Context) interface{} {
	m := make(map[string]interface{})
	m["module"] = "admin"
	m["name"] = "筱怪"
	m["age"] = 20

	ctx := g.Request.Context()

	// test logger
	cv, err := json.Marshal(m)
	ctxCache := facede.CtxCache(ctx)
	ctxLogger := facede.CtxLogger(ctx)
	ctxDB := facede.CtxDB(ctx)

	sv, err := ctxCache.Set("xg", cv, time.Second*100)
	ctxLogger.Infof("set cache res,sv:[%s] err:[%#v]", sv, err)

	v, err := ctxCache.Get("xg")
	ctxLogger.Infof("get cache res,sv:[%s] err:[%#v]", v, err)

	ctxLogger.Info("success")
	ctxLogger.Info("res: ", m)

	// test db
	var menu map[string]interface{}
	if err := ctxDB.Table("goadmin_menu").Where("id=?", 1).Find(&menu).Error; err != nil {
		ctxLogger.Errorf("query failed, err:[%#v]", err)
	}
	ctxLogger.Infof("query success, row:[%#v]", menu)

	logger.Info("call api success")

	return ghttp.Success(m)
}

func (u *UserInfo) List(g *gin.Context) interface{} {
	type ListInfo struct {
		PageIndex    int    `json:"pageIndex" form:"pageIndex"`
		PageSize     int    `json:"pageSize" form:"pageSize"`
		DepartmentId string `json:"departmentId" form:"departmentId"`
		Username     string `json:"username" form:"username"`
		Account      string `json:"account" form:"account"`
	}

	var info ListInfo
	if err := g.ShouldBindQuery(&info); err != nil {
		return ghttp.Fail(-1, "用户信息错误:"+err.Error())
	}

	userList := admin.GetUserList()
	pageList := mhelper.Pagination(userList, info.PageIndex, info.PageSize)

	return ghttp.Success(gin.H{
		"total": len(userList),
		"list":  pageList,
	})
}

func (u *UserInfo) Save(g *gin.Context) interface{} {
	type UserInfo struct {
		Username   string `json:"username"`
		Account    string `json:"account"`
		Department struct {
			DepartmentName string    `json:"departmentName"`
			CreateTime     time.Time `json:"createTime"`
			Status         int       `json:"status"`
			Id             string    `json:"id"`
			Remark         string    `json:"remark"`
		} `json:"department"`
		Role       []string  `json:"role"`
		Email      string    `json:"email"`
		CreateTime time.Time `json:"createTime"`
		Id         string    `json:"id"`
	}

	var user UserInfo
	if err := g.ShouldBindJSON(&user); err != nil {
		return ghttp.Fail(-1, "用户信息错误:"+err.Error())
	}
	return ghttp.Success(nil)
}

func (u *UserInfo) Delete(g *gin.Context) interface{} {
	type DeleteInfo struct {
		Ids []string `json:"ids"`
	}
	var info DeleteInfo
	if err := g.ShouldBindJSON(&info); err != nil {
		return ghttp.Fail(-1, "用户信息错误:"+err.Error())
	}
	return ghttp.Success(nil)
}
